import { ref, onMounted, onUnmounted } from 'vue'
import { throttle } from 'underscore'

export default function useScroll(reachBottomCB) {
  const scrollTop = ref(0);
  const scrollHeight = ref(0);
  const clientHeight = ref(0);

  const windowScrollHandler = throttle(() => {
    scrollTop.value = document.documentElement.scrollTop;
    clientHeight.value = document.documentElement.clientHeight;
    scrollHeight.value = document.documentElement.scrollHeight;
    if (scrollTop.value + clientHeight.value + 1 >= scrollHeight.value) {
      if (reachBottomCB) {
        reachBottomCB()
      };
    }
  }, 100)

  onMounted(() => {
    window.addEventListener('scroll', windowScrollHandler);
  })

  onUnmounted(() => {
    window.removeEventListener('scroll', windowScrollHandler);
  })

  return { scrollHeight, scrollTop, clientHeight };
}

